package com.liuqi.loggers.core.converters;

import com.liuqi.loggers.core.Converter;
import com.liuqi.loggers.core.LoggerEvent;
import java.io.ByteArrayOutputStream;

/**
 * Converter %throwable
 *
 * @author liuqi
 * @date 2024/11/5 16:57
 **/
public class ThrowableConverter implements Converter {

    private static String LINE_SEPARATOR = System.getProperty("line.separator", "\n");

    public String convert(LoggerEvent event) {
        Throwable t = event.getThrowable();
        return t == null ? null : format(t);
    }

    @Override
    public String convert0(LoggerEvent event) {
        Throwable t = event.getThrowable();
        return t == null ? null : format(t);
    }

    @Override
    public String name() {
        return "throwable";
    }

    private static String format(Throwable t) {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        t.printStackTrace(new java.io.PrintWriter(buf, true));
        String expMessage = buf.toString();
        return LINE_SEPARATOR + expMessage;
    }

}

